import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useRepairStore = defineStore('repair', () => {
  // ==================== 工单提交表单数据 ====================
  
  // 当前步骤 (1-5)
  const currentStep = ref(1)
  
  // 表单数据
  const formData = ref({
    // Step 1: 服务类型
    serviceType: '', // IN_STORE, MAIL_IN, ON_SITE
    
    // Step 2: 设备信息
    deviceModel: '',
    deviceSn: '',
    purchaseDate: '',
    warrantyStatus: '', // IN_WARRANTY, OUT_WARRANTY, UNKNOWN
    
    // Step 3: 故障描述
    faultTypes: [], // 故障类型数组
    faultDescription: '',
    faultPhotos: [], // 图片URL数组
    
    // Step 4: 服务方式
    serviceCenterId: null,
    serviceCenterName: '',
    appointmentTime: '',
    contactPhone: '',
    contactName: '',
    returnAddressId: null,
    pickupAddressId: null,
    
    // Step 5: 其他
    agreedToTerms: false
  })
  
  // ==================== 当前工单详情 ====================
  
  const currentOrder = ref(null)
  
  // ==================== 工单列表 ====================
  
  const orderList = ref([])
  const orderListTotal = ref(0)
  
  // ==================== Computed ====================
  
  // 是否可以进入下一步
  const canGoNext = computed(() => {
    switch (currentStep.value) {
      case 1:
        return !!formData.value.serviceType
      case 2:
        return !!(formData.value.deviceModel && formData.value.deviceSn)
      case 3:
        return !!(formData.value.faultTypes.length > 0 && formData.value.faultDescription)
      case 4:
        if (formData.value.serviceType === 'IN_STORE') {
          return !!(formData.value.serviceCenterId && formData.value.contactPhone)
        } else if (formData.value.serviceType === 'MAIL_IN') {
          return !!(formData.value.returnAddressId && formData.value.contactPhone)
        } else if (formData.value.serviceType === 'ON_SITE') {
          return !!(formData.value.serviceCenterId && formData.value.appointmentTime && formData.value.contactPhone)
        }
        return false
      case 5:
        return formData.value.agreedToTerms
      default:
        return false
    }
  })
  
  // 表单完成度
  const formProgress = computed(() => {
    return (currentStep.value / 5) * 100
  })
  
  // ==================== Actions ====================
  
  // 下一步
  function nextStep() {
    if (currentStep.value < 5 && canGoNext.value) {
      currentStep.value++
    }
  }
  
  // 上一步
  function prevStep() {
    if (currentStep.value > 1) {
      currentStep.value--
    }
  }
  
  // 跳转到指定步骤
  function goToStep(step) {
    if (step >= 1 && step <= 5) {
      currentStep.value = step
    }
  }
  
  // 重置表单
  function resetForm() {
    currentStep.value = 1
    formData.value = {
      serviceType: '',
      deviceModel: '',
      deviceSn: '',
      purchaseDate: '',
      warrantyStatus: '',
      faultTypes: [],
      faultDescription: '',
      faultPhotos: [],
      serviceCenterId: null,
      serviceCenterName: '',
      appointmentTime: '',
      contactPhone: '',
      contactName: '',
      returnAddressId: null,
      pickupAddressId: null,
      agreedToTerms: false
    }
  }
  
  // 更新表单数据
  function updateFormData(data) {
    formData.value = { ...formData.value, ...data }
  }
  
  // 设置当前工单
  function setCurrentOrder(order) {
    currentOrder.value = order
  }
  
  // 更新工单列表
  function setOrderList(list, total) {
    orderList.value = list
    orderListTotal.value = total
  }
  
  // 添加故障图片
  function addFaultPhoto(url) {
    if (formData.value.faultPhotos.length < 9) {
      formData.value.faultPhotos.push(url)
    }
  }
  
  // 删除故障图片
  function removeFaultPhoto(index) {
    formData.value.faultPhotos.splice(index, 1)
  }
  
  // 保存草稿到本地存储
  function saveDraft() {
    try {
      localStorage.setItem('repair_draft', JSON.stringify({
        step: currentStep.value,
        data: formData.value,
        timestamp: Date.now()
      }))
    } catch (e) {
      console.error('保存草稿失败:', e)
    }
  }
  
  // 从本地存储加载草稿
  function loadDraft() {
    try {
      const draft = localStorage.getItem('repair_draft')
      if (draft) {
        const { step, data, timestamp } = JSON.parse(draft)
        // 草稿有效期7天
        if (Date.now() - timestamp < 7 * 24 * 60 * 60 * 1000) {
          currentStep.value = step
          formData.value = data
          return true
        }
      }
    } catch (e) {
      console.error('加载草稿失败:', e)
    }
    return false
  }
  
  // 清除草稿
  function clearDraft() {
    try {
      localStorage.removeItem('repair_draft')
    } catch (e) {
      console.error('清除草稿失败:', e)
    }
  }
  
  return {
    // State
    currentStep,
    formData,
    currentOrder,
    orderList,
    orderListTotal,
    
    // Computed
    canGoNext,
    formProgress,
    
    // Actions
    nextStep,
    prevStep,
    goToStep,
    resetForm,
    updateFormData,
    setCurrentOrder,
    setOrderList,
    addFaultPhoto,
    removeFaultPhoto,
    saveDraft,
    loadDraft,
    clearDraft
  }
})

